<!DOCTYPE html>
<html>
<head>
<script src="../../../resources/js-test.js"></script>
<script src="../resources/common.js"></script>
</head>
<body>
<p id="description"></p>
<div id="console"></div>

<script>
description("Test generating, importing and exporting keys for AES-KW. Test that they can't be used with another algorithm.");

jsTestIsAsync = true;

var extractable = true;

// Globals used by tests
var key = null;
var exportedKey = null;

// Assigns the global |key| which is used by subsequent tests.
function generateTestKey()
{
    return expectSuccess(
        "Generating a key...",
        crypto.subtle.generateKey({name: "aes-kw", length: 256}, extractable, ["wrapKey", "unwrapKey"])
    ).then(function(result) {
        key = result;
        shouldBe("key.toString()", "'[object CryptoKey]'");
        shouldBe("key.type", "'secret'");
        shouldBe("key.algorithm.name", "'AES-KW'");
        shouldBe("key.algorithm.length", "256");
    });
}

function testWrongAlgorithm()
{
    var iv = hexStringToUint8Array("000102030405060708090a0b0c0d0e0f");

    return expectFailure(
        "Testing that the key can't be used with AES-CBC...",
        crypto.subtle.wrapKey("raw", key, key, {name: "AES-CBC", iv: iv}));
}

function testExportKey()
{
    return expectSuccess(
        "Exporting the key to raw...",
        crypto.subtle.exportKey('raw', key)
    ).then(function(result) {
        exportedKey = result;
        shouldBe("exportedKey.toString()", "'[object ArrayBuffer]'");
    });
}

function testImportExportedKey()
{
    return expectSuccess(
        "Importing it back...",
        crypto.subtle.importKey('raw', exportedKey, {name: "aes-kw"}, extractable, ["wrapKey", "unwrapKey"])
    ).then(function(result) {
        importedKey = result;

        shouldBe("importedKey.toString()", "'[object CryptoKey]'");
        shouldBe("importedKey.type", "'secret'");
        shouldBe("importedKey.algorithm.name", "'AES-KW'");
        shouldBe("importedKey.algorithm.length", "256");
    });
}

Promise.resolve(null)
    .then(generateTestKey)
    .then(testWrongAlgorithm)
    .then(testExportKey)
    .then(testImportExportedKey)
    .then(finishJSTest, failAndFinishJSTest);

</script>

</body>
</html>
